#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import	socket
import	asyncore

class	UDPServer(asyncore.dispatcher) :
	MAX_PACKET_SIZE = 65536 - 4096

	def	__init__(self, port) :
		asyncore.dispatcher.__init__(self)
		self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
		self.set_reuse_addr()
		self.bind(('', port))
		self.socket.settimeout(1.0)
		self.__queue_out = []

	def	handle_read(self) :
		try :
			data, peer_addr = self.socket.recvfrom(self.MAX_PACKET_SIZE)
			# call callback()
			self.__queue_out.append( (data, peer_addr) )
			print data

		except socket.timeout, why :
			print why
			pass


	def	handle_connect(self) :
		print 'handle_connect ...'
		pass

	def	handle_close(self) :
		print 'handle_close ...'
		self.close()

	def	handle_accept(self) :
		print 'handle_accept ...'
		pass

	def	writable(self) :
		return	len(self.__queue_out) > 0

	def	handle_write(self) :
		#print 'handle_write ...'
		for data, addr in self.__queue_out :
			try :
				self.socket.sendto( data, 0, addr )
			except socket.timeout :
				pass
		self.__queue_out = []

if	__name__ == '__main__' :
	server = UDPServer( 4344 )

	asyncore.loop()

